package de.backtomedieval.main;

import java.util.ArrayList;

import de.backtomedieval.R;
import de.backtomedieval.research.AbstractResearch;
import de.backtomedieval.scenarios.AbstractDefendYourCityScenario;
import de.backtomedieval.scenarios.AbstractScenario;
import de.backtomedieval.units.UnitSet;
import de.backtomedieval.activities.gamemenu.Buildmenu;
import de.backtomedieval.activities.gamemenu.FightScreen;
import de.backtomedieval.activities.gamemenu.Gamemenu;
import de.backtomedieval.activities.gamemenu.ViewUnits;
import de.backtomedieval.game.City;
import de.backtomedieval.game.Fight;
import de.backtomedieval.game.Player;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import android.util.Log;


public class Game {

	public static final String PREFS_NAME = "GAMEPREFS";

	public static final boolean DEBUG = false;
	
	private static Thread timerThread;
	private static boolean gamePaused = false;
	private static int gamespeed = 1000;
	private static int[] gamespeeds = {3500,2500,1500,750,500,250,50,1};
	private static Activity lastActivity;
	private static boolean gameStarted = false;
	private static int difficulty = 2;
	private static Game game;
	private long roundnr = 1;
	private ArrayList<Player> players = new ArrayList<Player>();
	private AbstractScenario scenario = null;
	private boolean gameActive = true;
	private static boolean pauseOnEndOfFight = false;
	private static boolean pauseOnStartOfFight = false;
	private static boolean pauseOnGameStart = false;
	private static String playername="";
	private static String cityname ="";
	
	
	
	public static String getPlayername() {
		return playername;
	}

	public static void setPlayername(String playername) {
		Game.playername = playername;
	}

	public static String getCityname() {
		return cityname;
	}

	public static void setCityname(String cityname) {
		Game.cityname = cityname;
	}

	public Game() {
		Game.game=this;
	}

	public static int getRefreshrate() {
		if (gamespeed>500) {
			return gamespeed;
		} else {
			return 500;
		}
	}

	public long getRoundnr() {
		return roundnr;
	}

	public void setRoundnr(long roundnr) {
		this.roundnr = roundnr;
	}

	public boolean isGameActive() {
		return gameActive;
	}

	public void setGameActive(boolean gameActive) {
		this.gameActive = gameActive;
	}
	
	public ArrayList<Player> getPlayers() {
		return players;
	}

	public void setPlayers(ArrayList<Player> players) {
		this.players = players;
	}
	
	public Player getPlayer() {
		return players.get(0);
	}

	public static boolean isGamePaused() {
		return gamePaused;
	}
	
	public City getcCity() {
		return this.players.get(0).getCurrentCity();
	}

	public static void setGamePaused(boolean gamePaused) {
		Game.gamePaused = gamePaused;
	}
	
	public static int getDifficulty() {
		return difficulty;
	}

	public static void setDifficulty(int difficulty) {
		Game.difficulty = difficulty;
	}

	private static AbstractScenario startScenario = null;

	private static ArrayList<City> m_citys;
		
	public static void showPopup(String message) {
		Context context = lastActivity.getApplicationContext();
		CharSequence text = message;
		int duration = Toast.LENGTH_SHORT;
		Toast.makeText(context, text, duration).show();
	}
	
	public static void showPopup(Activity a, String message) {
		Context context = a.getApplicationContext();
		CharSequence text = message;
		int duration = Toast.LENGTH_SHORT;
		Toast.makeText(context, text, duration).show();
	}
	
	public static void startRoundTimer() {
		timerThread = new Thread(new Runnable() {
			    public void run() {
			    	do {
			    		try {
							Thread.sleep(gamespeed);
						} catch (InterruptedException e) {
						}
			    		if (!gamePaused) Game.getGame().nextRound();
			    		if (!gamePaused) Fight.fightRounds();
			    		
			    	} while(Game.getGame().isGameActive() && gameStarted);
			    }
			  });
		timerThread.start();
	}
	
	public void nextRound() {
		if (!gameActive) return;
		if (players.size() == 0) return;
		for (int i=0; i<players.size();i++) {
			players.get(i).nextRound();
		}
		roundnr = roundnr + 1;
		if (scenario!=null) {
			scenario.checkWinConditions(this);
		}
	}
	
	public AbstractScenario getScenario() {
		return scenario;
	}

	public void setScenario(AbstractScenario scenario) {
		this.scenario = scenario;
	}

	
	
	public static void startGame() {
		Game.setGamePaused(Game.isPauseOnGameStart());
		gameStarted=true;
		startRoundTimer();
	}
	
	public static void endGame() {
		gameStarted=false;
	}
	
	
	public static Activity getLastActivity() {
		return lastActivity;
	}

	public static void setLastActivity(Activity lastActivity) {
		Game.lastActivity = lastActivity;
	}

	public static void setGameSpeed(int index) {
		if (index >= 0 && index<gamespeeds.length)
		gamespeed = gamespeeds[index];
	}
	
	public static void stopRoundTimer() {
		timerThread.stop();		
	}

	public static void setStartScenario(AbstractScenario startScenario) {
		Game.startScenario = startScenario;
	}

	public static AbstractScenario getStartScenario() {
		return startScenario;
	}

	public static String getString(int id) {
		return lastActivity.getString(id);
	}

	public static SharedPreferences getSharedPreferences(String prefsName, int i) {
		return lastActivity.getSharedPreferences(prefsName,i);
	}

	public static String[] getStringArray(int id) {
		Resources res = lastActivity.getResources();
		return res.getStringArray(id);
	}

	public static void setGame(Game game) {
		Game.game = game;
	}

	public static Game getGame() {
		return game;
	}

	public void addPlayer(Player player) {
		players.add(player);
	}

	public static void setPauseOnEndOfFight(boolean pauseOnEndOfFight) {
		Game.pauseOnEndOfFight = pauseOnEndOfFight;
	}

	public static boolean isPauseOnEndOfFight() {
		return pauseOnEndOfFight;
	}

	public void showChangeCityDialog(final Activity caller) {
		final boolean isPause;
		if (Game.isGamePaused()) {
			isPause = true;
		} else {
			isPause = false;
			Game.gamePaused=true;
		}
		final ArrayList<City> citys = Game.getGame().getPlayer().getCitys();
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(caller);
        builder.setTitle(Game.getString(R.string.changecity));
        builder.setAdapter(new CityAdapter(caller, R.layout.row, citys),new android.content.DialogInterface.OnClickListener(){
			@Override
			public void onClick(android.content.DialogInterface dialog,
					int item) {
                Game.getGame().getPlayer().setCurrentCity(citys.get(item));
                if (caller instanceof Buildmenu) {
                	((Buildmenu) caller).changedCity();
                }
                Game.gamePaused=isPause;
                return;
			}
        });
        builder.create().show();
	}
	
	public static void setPauseOnStartOfFight(boolean pauseOnStartOfFight) {
		Game.pauseOnStartOfFight = pauseOnStartOfFight;
	}

	public static boolean isPauseOnStartOfFight() {
		return pauseOnStartOfFight;
	}

	public static void setPauseOnGameStart(boolean pauseOnGameStart) {
		Game.pauseOnGameStart = pauseOnGameStart;
	}

	public static boolean isPauseOnGameStart() {
		return pauseOnGameStart;
	}

	private class CityAdapter extends ArrayAdapter<City> {

	    private ArrayList<City> items;

	    public CityAdapter(Context context, int textViewResourceId, ArrayList<City> items) {
	            super(context, textViewResourceId, items);
	            this.items = items;
	    }

	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	            View v = convertView;
	            if (v == null) {
	                LayoutInflater vi = (LayoutInflater)lastActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	                v = vi.inflate(R.layout.row, null);
	            }
	            City o = items.get(position);
	            if (o != null) {
	                    TextView tt = (TextView) v.findViewById(R.id.toptext);
	                    TextView bt = (TextView) v.findViewById(R.id.bottomtext);
	                    ImageView icon=(ImageView)v.findViewById(R.id.icon);
	                     icon.setImageResource(R.drawable.city);
	                    if (tt != null) {
	                          tt.setText(o.getName());
	                          tt.setTextColor(Color.BLACK);
	                    }
	                    if(bt != null){
	                    	
	                    }
	            }
	            return v;
	    }
	}


	
		
	
	
}
